// 全局变量
var _global = {
    isLoading: false,
    isFontChanged: false,
    cacher: new CacheHelper(),
    jstrer: new JsonStrHelper(),
	promote: new PopupClass(),
    uploadId : new loadImageEvent(),
    checkPhoner: new loadVerifyPhone(),
	isResend: true,
	isDiyLazyLoad: false,
    requires: {},
    thrower: null,
    throwerID: 0,
	isWeiXinLoad: false,
	isLogin: false,
	isStopSell: false,
	mbReg: /^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17\d{9}$|^18[\d]{9}$/
};
// require全局配置
require.config({
    baseUrl: "/Public/Home/js",
    paths: {
         "jquery": "jquery.min",
         "swiper":"swiper.min",
         "Bswiper":"swiper-3.4.0.jquery.min",
         "pincode": 'pincode-input',
         "ajaxupload" : "jquery.ajaxfileupload",
         "countdown" : "jquery.countdown.min"
    },
    shim: {
        'pincode': ['jquery'],
        'Bswiper':['jquery'],
        'swiper':['jquery'],
        'ajaxupload':['jquery'],
        'countdown':['jquery']
    }
});

_global.jstrer.setData(_global.cacher.get("history") || "");

writeLoading();  
// 加载正在处理
function writeLoading(){
    var _LoadingHtml = '<div id="loadingDiv" style="background-color:#fff;background-repeat:no-repeat;background-size:100px 100px;background-image:url(/Public/Home/images/loading.gif);background-position:center center;width:100%;height:100%;overflow:hidden;z-index:10000;position:fixed;left:0;top:0;"></div>';  
	var tjContent = "佳坊怡臣停购通知！由于佳坊怡臣生活超市将进行内部休整，从5月5日开始暂停线上购物，请各位朋友从现在开始不要在佳坊怡臣生活超市进行购物（永立百货不影响），已经购物而没发货朋友的订单将进行人工退款。佳坊怡臣线上店将于5月6日关闭，重新开启时间另行通知。";
	var _stopSellHTML = '<div id="stopSellDiv" style="background:#fff;border:0.04rem solid #c40000;width:5.0rem;height:4.5rem;padding:0.2rem;overflow:auto;color:#c40000;font-size:0.30rem;line-height:1.5;z-index:99999;display:none;position:fixed;top:1.0rem;left:50%;margin-left:-2.5rem;">'+tjContent+'</div>';
    document.write(_LoadingHtml+_stopSellHTML);
    //监听加载状态改变  
    document.onreadystatechange = completeLoading;
}
  
// 加载状态为complete时并且字体设置后移除loading效果
function completeLoading() {
    if (document.readyState == "complete" && _global.isFontChanged && !_global.isLoading) {		
        setTimeout(function(){
            if(_global.isLoading) return;
            _global.isLoading = true;			
            var loadingMask = document.getElementById('loadingDiv');
			if(_global.isStopSell){
				document.getElementById('stopSellDiv').style.display = "block";
			}
            loadingMask.parentNode.removeChild(loadingMask);
            if(!_global.isDiyLazyLoad){
                imgLazyLoad();
            }
        }, 500);
    }
}
String.prototype.trim = function(){
	return this.replace(/^\s+/, "").replace(/\s+^/, "");	
}
function imgLazyLoad(){
    $(".img-lazyload").lazyload({
        effect: "fadeIn",
        load: function(o){
            o.removeClass("img-lazyload");
        }
    });
}
function decodeHTMLSpecialChars(str){
	if(str){
		str = str.replace(/&amp;/g, "&");
		str = str.replace(/&lt;/g, "<");
		str = str.replace(/&gt;/g, ">");		
		str = str.replace(/&nbsp;/g, " ");
		str = str.replace(/&quot;/g, "\"");
		str = str.replace(/&copy/g, "@c");
		return str;
	}
	return "";
}
// 获取默认图片地址,如果没有图片的话
function getDefaultImg(imgSrc, isUpload){
	var len = arguments.length;
	var ext = (len == 2 && isUpload) ? "/Uploads/" : "";
	if(imgSrc !== undefined && imgSrc.indexOf(".") != -1){
		return ext + imgSrc;
	}else{		
		return "/Public/Home/images/blank.png";
	}
}
// 设置HTML字体大小
function setRootFontSize(pageSetSize){
    if(_global.isFontChanged)
        return;
    pageSetSize.htmlFontSize();
    _global.isFontChanged = true;
    completeLoading();
}
// 设置一个指定的require模块配置 
// setRequire('menu', {path : '/public/modules/menu'})
function setRequire(key, config){
    _global.requires[key] = config;
}

// 加载所有配置的require模块文件
function loadRequires(){
    var cmodule;
    for(var k in _global.requires){
        cmodule = _global.requires[k];
        require(cmodule.path);
    }
}
// 数组字符串转换器(针对键值对)
function JsonStrHelper(){
    var data = "";
    var jsonArr = [];
    var isExist = function(key){
        var flag = false;
        for(var i = 0;i < jsonArr.length;i++){
            if(jsonArr[i].key == key){
                flag = true;
                break;
            }
        }
        return flag;
    };
    this.setData = function(v){
        data = v;
        jsonArr = this.getArrayByStr(v);
    };
    this.setItem = function(key, val){
        if(isExist(key)){
            return;
        }
        data += (data != "" ? "," : "") + encodeURIComponent(key) + "=" + encodeURIComponent(val);
        jsonArr.push({key : key, val : val});
    };
    this.getArrayByStr = function(str){
        var rs = [];
        var str = str || "";
        if(str == "") return rs;
        var arr = str.split(",");
        var c = "";
        var cj = [];
        for(var i = 0;i < arr.length;i++){
            c = arr[i];
            cj = c.split("=");
            rs.push({key : decodeURIComponent(cj[0]), val: decodeURIComponent(cj[1])});
        }
        return rs;
    };
    this.getArr = function(){
        return jsonArr;
    };
    this.getData = function(){
        return data;
    };
}
// 缓存帮助器
function CacheHelper(){
    this.set = function(key, val){
        window.localStorage.setItem(key, val);
    };
    this.get = function(key){
        return window.localStorage.getItem(key);
    };
    this.remove = function(key){
        window.localStorage.removeItem(key);
    };
    this.clear = function(){
        window.localStorage.clear();
    };
}
function repeatStr(str, times){
    var rs = "";
    for(var i = 0; i < times; i++){
        rs += str;  
    }
    return rs;
}
// 获取精准浮点(只保证小数点为两位的)
// 相乘时要求v2是整数
function getFixedFloat(v1, v2, op){
    v1 = v1.toString();
    v2 = v2.toString();
	var isFs1 = v1.indexOf("-") == 0;
	var isFs2 = v2.indexOf("-") == 0;
	var isDoubleFs = false;
	if(isFs1 && isFs2){
		v1 = v1.substring(1);
		v2 = v2.substring(1);
		isDoubleFs = true;
	}else if(isFs1){
		v1 = v1.substring(1);
		if(op == "-"){			
			isDoubleFs = true;
			op = "+";		
		}else if(op == "+"){
			var tmp = v1;
			v1 = v2;
			v2 = tmp;
			op = "-";
		}
	}else if(isFs2){
		v2 = v2.substring(1);
		if(op == "-"){
			op = "+";		
		}else if(op == "+"){
			op = "-";
		}
	}
    var v1Arr = v1.split(".");
    var v2Arr = v2.split(".");
    var cMax = 1;
    if(v1Arr.length == 1){
        v1Arr.push("0");
    }else{
        cMax = v1Arr[1].length;
        if(cMax == 1){
            v1Arr[1] = v1Arr[1] + "0";
            cMax = 2;
        }        
    }    
    if(v2Arr.length == 1){
        v2Arr.push("0");
    }else{
        var fdlen2 = v2Arr[1].length;
        if(fdlen2 > cMax){            
            v1Arr[1] = v1Arr[1].toString() + repeatStr("0", fdlen2 - cMax);
            cMax = fdlen2;
        }else if(fdlen2 < cMax){
            v2Arr[1] += repeatStr("0", cMax - fdlen2);
        }
        cMax = 2;
    }	
    for(var i = 0; i < 2; i++){
        v1Arr[i] = parseInt(v1Arr[i]);
        v2Arr[i] = parseInt(v2Arr[i]);
    }	
    var rs = 0;
    var jsArr = [0, 0];
    var isMinus = false;
    var isReverse = false;
    if(op == "+"){
        jsArr[0] = v1Arr[0] + v2Arr[0];
        jsArr[1] = v1Arr[1] + v2Arr[1];
    }else if(op == "-"){
        if(v1Arr[0] < v2Arr[0] || (v1Arr[0] == v2Arr[0] && v1Arr[1] < v2Arr[1])){
            jsArr[0] = v2Arr[0] - v1Arr[0];
            jsArr[1] = v2Arr[1] - v1Arr[1];
            isReverse = true;
        }else{
            jsArr[0] = v1Arr[0] - v2Arr[0];
            jsArr[1] = v1Arr[1] - v2Arr[1];
        }
        isMinus = true;
    }else if(op == "*"){
        jsArr[0] = v1Arr[0] * v2Arr[0];
        jsArr[1] = v1Arr[1] * v2Arr[0];
    }
    var xsstr = jsArr[1].toString();
    var dlen = xsstr.length - cMax;
    if(dlen > 0 && !isMinus){
        jsArr[0] += parseInt(xsstr.substr(0, dlen));
        xsstr = xsstr.substr(dlen);        
    }else if(isMinus){
        if(jsArr[0] > 0 && jsArr[1] < 0){            
            jsArr[1] += 100;
            jsArr[0] -= 1;
        }
        xsstr = jsArr[1].toString();
    }
    if(xsstr.length == 1){
        xsstr = "0" + xsstr;
    }
	var rs = "";
	var isZero = parseInt(jsArr[0]) == 0 && parseInt(xsstr) == 0;
	if(isDoubleFs){
		if(isReverse && op == "-"){
			rs = jsArr[0] + "." + xsstr;
		}else if(op == "-" || op == "+"){
			rs = (isZero ? "" : "-") + jsArr[0] + "." + xsstr;
		}
	}else{
		rs = (isReverse ? "-" : "") + jsArr[0] + "." + xsstr;
	}
    return rs;
}
// 检查搜索关键字,并将其存入缓存
function checkSearch(){
    var kw = $("input[name='keywords']");
    if(kw.val() == "")
        return true;
    //var val = encodeURIComponent(kw.val());
    var val = kw.val();
    // var eurl = "/Search/index?keywords="+val;
    var eurl = "/Search/index"+getFixedExtraUrl()+"?keywords="+val;
    _global.jstrer.setItem(val, eurl);
    _global.cacher.set("history", _global.jstrer.getData());
    return true;
}
// 载入历史搜索记录
function loadSearchRecords(){
    var rs = "";
    var arr = _global.jstrer.getArr();
    for(var i = 0;i < arr.length;i++){
        rs += "<a href=\""+arr[i].val+"\">"+arr[i].key+"</a>";  
    }
    if(rs == ""){
        $("#search-history-box").css("display", "none");
    }else{
        $("#search-history-list").html(rs);
    }
    
}
// 运行购物车弹球飞入效果
function runBallEffect(e){
    _global.throwerID++;
    var cid = _global.throwerID;
    $('body').append('<div id="unique-cart-ball'+cid+'" class="unique-cart-ball"></div>');
    var thrower = new Parabola();
    thrower.el =  $("#unique-cart-ball"+cid);
    thrower.duration = 700;
    thrower.callback = function(){
        thrower.el.css("display", "none");
		thrower.el.remove();
        delete thrower;
    };
    var x = e.pageX || e.clientX;
    var y = e.pageY || e.clientY;
    var unOff = $("#unique-cart-number").offset();
    thrower.el.css({"left" : x+"px", "top" : y+"px"});
    thrower.el.css("display", "block");
    thrower.setPositions([x, y], [unOff.left, unOff.top]);
    thrower.start();    
}
// 弹出框提取
function PopupClass(){
    // 无效果弹窗
    this.popup = function(obj, isOnlyOne){
        var _obj = $(obj);
		var isOnlyOne = isOnlyOne || false;
        _obj.show();
        $('body').append('<div class="pop-mask"></div>');
		if(isOnlyOne) return;
        _obj.find('.close,.cancel,.confirm').on('click',function(){
            _obj.hide();
            $('.pop-mask').remove();
        });
    };
    // 向上弹窗
    this.popupSlide = function(obj){
        var _obj = $(obj);
        _obj.slideDown(200);
        $('body').append('<div class="pop-mask"></div>');
        _obj.find('.close,.cancel,.cart-sure').on('click',function(){
            _obj.slideUp(200);
            $('.pop-mask').remove();
        });
    };
    //提示弹窗
    this.alertPopup = function(txt, isLong){
        var alert_tips ='<div class="alertTips">'+txt+'</div>'; 
        var isLong = isLong || false;
        var speed = isLong  ? 3000 : 1000;
        $('body').append(alert_tips);
        setTimeout(function(){
            $('.alertTips').fadeOut(function(){$(this).remove()});
        },speed);
    };
    //正在处理弹窗
    this.loadPopup = function(txt, isMoreTier){
		var txt = txt || "正在处理中...";
        var isMoreTier = isMoreTier || false;
        if(isMoreTier){
            var load_tips ='<div class="alert-popup data-progressing" style="display:block;z-index:105">'; 
            load_tips += '<i class="load-pic"></i><span class="txt">'+txt+'</span>';
            load_tips += '</div><div id="data-progress-load" class="pop-mask" style="z-index:104"></div>';    
        } else{
            var load_tips ='<div class="alert-popup data-progressing" style="display:block;">'; 
            load_tips += '<i class="load-pic"></i><span class="txt">'+txt+'</span>';
            load_tips += '</div><div id="data-progress-load" class="pop-mask"></div>';
        }
        $('body').append(load_tips);
    };
    //移除正在处理提示
    this.removeLoad = function(){
        $(".data-progressing").remove();
        $("#data-progress-load").remove();
    };
}
// 拼接Url参数后缀,解决local_id无法获取的问题  示例："/Home/test"+getFixedExtraUrl()  不能紧跟在/后面
// excl_nm 排除的键值名称
function getFixedExtraUrl(excl_nm){
    var rs = "";
    if(yc_pass_arr){
        for(var k in yc_pass_arr){
			if(excl_nm == k){
				continue;	
			}
            rs += "/"+k+"/"+yc_pass_arr[k];
        }
    }
    return rs;
}
// 加载手机验证处理
function loadVerifyPhone(){
    var _phone_val;
    var _self_el;
    var _self = this;
    var _isRun = false;
    var _isLoadEvents = false;
    var _isCheckAllowed = false;
    var _tzhref = "";
    this.run = function(e, tzhref){
        e.preventDefault();
        _tzhref = tzhref || "";
		if(_global.isLogin){
			_self.succfunc();
			return;
		}
        if(!_isLoadEvents){
            $('.bindPhone-box').addClass('bindPhone-none');
            bindEvents();
            _isLoadEvents = true;
        }
        if(_isRun) return;
        _isRun = true;
        $.ajax({
            type: "get",
            url: "/Home/Letter/verify"+getFixedExtraUrl(),
            dataType: "json",
            success: function(rs) {
                if(!_self.verifyfunc(rs, tzhref)) {
                    yzIphoneMes();
                }else{
					_global.isLogin = true;
				}
                _isRun = false;
            },
            error: function(){
                _global.promote.alertPopup("服务器异常,请稍后重试！");
                _isRun = false;
            }
        });
    };
    this.runOnlyPhone = function(e, tzhref){
        e.preventDefault();
		if(!_isLoadEvents){          
            bindEvents();
            _isLoadEvents = true;
        }
        if(_isRun) return;
        _isRun = true;
        _global.promote.popup('.bindPhone-box');
        $('.bindPhone-box').removeClass('bindPhone-none');
        _isRun = false;
    };
    this.reset = function(){
        _self.verifyfunc = function(rs, url){
            if(rs){
                if(url!=='') window.location.href = url;
                return true;
            }else{
                return false;
            }
        };
        _self.succfunc = function(){
            if(_tzhref !== ""){
                window.location.href = _tzhref;
            }else{
                window.location.href = "/Home/Member/index"+getFixedExtraUrl();
            }
        };
    };
    this.reset();
    // 绑定事件
    function bindEvents(){
        // 验证码
        $('#yzCaptcha').bind('click', function(e) {
            if(!_isCheckAllowed)
                return;
            if(!_global.isResend){
                return;
            }
            e.preventDefault();
            _global.isResend = false;
            $(this).css({'background': '#dae2e2', 'color': '#919896'});
            var set = $('#yzCaptcha').text();
            if(set.length == 5){
                $.ajax({
                    type: "get",
                    url: "/Home/Letter/verifyMobileCode"+getFixedExtraUrl(),
                    data: {
                        mobile: _phone_val
                    },
                    dataType: "json",
                    success: function(rs) {
                        if(rs.stat == true) {
                            timer(rs.data);
                            $('#pincode-list').hide();
                            $('#code-input').pincodeInput({
                                hidedigits:true,
                                complete:function(value){
                                    verifyCode(value);
                                }
                            });
                        } else {
                            _global.promote.alertPopup(rs.msg);
                        }
                    }
                });
            }
        });
        //打开手机验证框,校验手机输入的号码
        $('#phone').bind('change', function(e) {
            e.preventDefault();
            _self_el = $(this);
			_isCheckAllowed = false;
            // 验证手机号码是否符合标准
            _phone_val = $(this).val();
            var _myreg = _global.mbReg;
            if(!_phone_val) {
                _global.promote.alertPopup('请输入手机号');
                return false;
            }
            if(!_myreg.test(_phone_val)) {
                _self_el.val('');
                _global.promote.alertPopup('请输入正确手机号码');
                return false;
            }
            _self_el.css({color: '#444'});
            _isCheckAllowed = true;
        });
        //关闭验证手机框
        $('.bindPhone-box').find('.close').on('click', function() {
            $(this).parent().hide();
            $('#phone').val('');
        });
        //改变验证框效果
        $('#phone').keyup(function() {
            $(this).siblings().css({'background': '#3c6a63','color': '#fff'});
        });
    }
    //&未绑定手机请绑定手机
    function yzIphoneMes() {
        $('.bindPhone').find('.close,.cancel,.confirm').off('click');
        _global.promote.popup('.bindPhone'); //弹窗 提示绑定手机
        $('.bindPhone .confirm').click(function() {
            $('.bindPhone-box').find('.close,.cancel,.confirm').off('click');
            _global.promote.popup('.bindPhone-box');
            $('.bindPhone-box').find('#phone').focus();
            $('.bindPhone-box').removeClass('bindPhone-none');
        })
    }
    // 倒计时方法
    function timer(intDiff) {
        var time = intDiff * 60; //倒计时总秒数量
        var ctimer = 0;
        var handler = function() {
            var second = 0; //时间默认值
            if(time > 0) {
                second = Math.floor(time);
            }else{
                clearInterval(ctimer);
                $('#yzCaptcha').css({'background': '#3c6a63','color': '#fff'}).html('重获验证码');
                _global.isResend = true;
                return;
            }
            if(second <= 9 && second > 0) second = '0' + second;
            $('#yzCaptcha').html('<s></s>' + second + '秒');
            time--;
            //yzCaptchaTime = $('#yzCaptcha').text().substring(0, 2);
        };
        $('#yzCaptcha').html('<s></s>' + Math.floor(time) + '秒');
        time--;
        ctimer = window.setInterval(handler, 1000);
    }
    // 验证码输入步骤
    function verifyCode(key) {
        $.ajax({
            type: "get",
            url: "/Home/Letter/verifyMobile"+getFixedExtraUrl(),
            data: {
                mobile: _phone_val,
                code: key
            },
            dataType: "json",
            success: function(rs) {
                if(rs.stat == true) {
                    $('.code-tips').hide();
                    $('.inputInfo').hide();
                    $('.success').show();
                    var timeout;
                    var count = 3; // 默认时间
                    var BtnCount = function() {
                        // 启动按钮
                        if (count == 0) {
                            clearTimeout(timeout);   // 可取消由 setTimeout() 方法设置的 timeout
                            $('.bindPhone-box').hide();
                            _self_el.val(''); //清空手机号码
                            $('.pop-mask').css({display:'none'});
                            //成功时候执行的方法
                            _self.succfunc();
                        }
                        else {
                            count--;
                            $('.success').find('i').text(count.toString());
                            setTimeout(BtnCount, 1000);
                        }
                    };
                    timeout = setTimeout(BtnCount, 1000); // 1s执行一次BtnCount
                } else {
                    $('.code-tips').show();
                    $('#code-input').pincodeInput().data('plugin_pincodeInput').clear();
                    $('#code-input').pincodeInput().data('plugin_pincodeInput').focus();
                    $('.code-tips').html(rs.msg);
                }
            }
        });
    }
}

// 微信自动配置
function wxAutoConfig(_opts){
	if(isInHeader){
		$(document).ready(function(){
			wxPrivateInvoke(_opts);
		});
	}else{
		wxPrivateInvoke(_opts);
	}	
}
function wxPrivateInvoke(_opts){
	//核心参数未定义
	var isDefined = !!_opts["config"].appId;
	if(!isDefined){
		return;	
	}
	var share_imgUrl = yc_wx_shareImgPath || "";
	var exts = [".png", ".jpg", ".gif"];
	if(!isWxShareDiy && share_imgUrl.length > 4){
		var ext = share_imgUrl.substr(-4);
		isWxShareDiy = true;
		for(var i = 0;i < exts.length;i++){
			if(ext == exts[i]){
				isWxShareDiy = false;
				break;	
			}	
		}				
	}else{
		isWxShareDiy = true;		
	}
	var imgList = $("img");
	if(isWxShareDiy && imgList.length > 0){
		var imgObj = imgList.eq(0);
		if(imgObj.attr("data-original")){
			share_imgUrl = imgObj.attr("data-original");
		}else{
			share_imgUrl = imgObj.attr("src");
		}	
	}
	share_imgUrl = share_imgUrl.indexOf("http") != -1 ? share_imgUrl : ("http://m.yichen666.com/"+share_imgUrl);
	var share_url = window.location.href;	/*'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+_opts["config"].appId+'&redirect_uri='+encodeURIComponent("http://weixin.yichen123.cn/Home/First/publicBase/?return_url="+encodeURIComponent(window.location.href))+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";*/
	_opts["config"]["jsApiList"].push("onMenuShareTimeline");//分享给朋友圈
	_opts["config"]["jsApiList"].push("onMenuShareAppMessage");	 //分享给朋友
    _opts["config"]["jsApiList"].push("chooseImage");   //拍照或从手机相册中选图
    _opts["config"]["jsApiList"].push("previewImage");  //预览图片
    _opts["config"]["jsApiList"].push("uploadImage");   //上传图片
    _opts["config"]["jsApiList"].push("downloadImage"); //下载图片
    wx.config(_opts["config"]);
    wx.ready(function () {  
        wx.checkJsApi({
            success: function (res) {
                if (res.checkResult.getLocation == false) {
					if(typeof _opts["refuseCallback"] == "function"){
						_opts["refuseCallback"]();	
					}
                    alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
                    return;
                }
            }
        });
		if(_opts["enableLocation"]){
			wx.getLocation({
				type : 'wgs84',
				success: function (res) {
					var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
					var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
					var speed = res.speed; // 速度，以米/每秒计
					var accuracy = res.accuracy; // 位置精度
					if(typeof _opts["mapCallback"] == "function"){
						_opts["mapCallback"](latitude, longitude);	
					}
				},
				cancel: function (res) {
					// 用户拒绝授权获取地理位置
					if(typeof _opts["refuseCallback"] == "function"){
						_opts["refuseCallback"]();	
					}
				}
			});
		}
		wx.onMenuShareTimeline({
			title: document.title, // 分享标题
			desc: '', // 分享描述
			link: share_url, // 分享链接	
			imgUrl: share_imgUrl, // 分享图标
			type: '', // 分享类型,music、video或link，不填默认为link
			dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
			success: function () { 
				// 用户确认分享后执行的回调函数
			},
			cancel: function () { 
				// 用户取消分享后执行的回调函数
			}
		});
		wx.onMenuShareAppMessage({
			title: document.title, // 分享标题
			desc: '', // 分享描述
			link: share_url, // 分享链接 
			imgUrl: share_imgUrl, // 分享图标
			type: '', // 分享类型,music、video或link，不填默认为link
			dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
			success: function () { 
				// 用户确认分享后执行的回调函数
			},
			cancel: function () { 
				// 用户取消分享后执行的回调函数
			}
		});	
    }); 
}


// 拍照或者选择照片

function loadImageEvent(){
    // 图片接口
    // 拍照、本地选图
    var images = {
        localId: [],
        serverId: []
    }; 

    this.selectImage = function(evt){
        var _self = evt; 
        //alert(111);
        wx.chooseImage({
            count: 1, // 默认9，这里每次只处理一张照片
            sizeType: ['original', 'compressed'],   // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'],        // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                images.localId = res.localIds;      // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片           
                var i = 0, length = images.localId.length; 
                function upload() { 
                    wx.uploadImage({ 
                        localId: images.localId[i], 
                        isShowProgressTips:1, // 默认为1，显示进度提示
                        success: function(res) { 
                            //alert(333);
                            i++; 
                            //alert('已上传：' + i + '/' + length); 
                            images.serverId.push(res.serverId);          
                            // res.serverId 就是 media_id，根据它去微信服务器读取图片数据：
                            _self.siblings().html(
                                '<div class="upload-item">' +
                                '<img src="'+ images.localId +'"/>' +
                                '</div>'
                            );
                            var indata = {"media_id":res.serverId};                            
                            $.get("/Home/Member/saveMedia", indata, function(rs){
                                if(rs.status){    
                                    _self.find('input').val(rs.data)                                                
                                    //_global.promote.alertPopup("上传成功");                                  
                                }else{
                                    _global.promote.alertPopup("服务器异常,请稍后重试！");
                                }
                              },'json');
                            if (i < length) { 
                                upload(); 
                            }                
                        }, 
                        fail: function(res) { 
                            _global.promote.alertPopup('上传失败');                
                        } 
                    }); 
                } 
                upload(); 
            } 
        });

    };
    this.previewImage = function(imgUrl){
        wx.previewImage({
                current: imgUrl, 
                urls: [imgUrl]
         });
    };  
}
